package com.ruoyi.system.util;

import com.ruoyi.common.utils.StringUtils;

public class MyUtil {
    public static String getSql(String str, String field) {
        if (str == null) {
            return null;
        }
        StringBuffer or = new StringBuffer();
        StringBuffer and = new StringBuffer();
        if (str.endsWith("&&")) {
            str.replace("&&", "");
        }
        if (str.startsWith("&&")) {
            if (str.length() > 2) {
                str = str.substring(2, 3) + str;
            } else {
                str.replace("&&", "");
            }
        }
        if (StringUtils.isEmpty(str)) {
            return str;
        } else {
            str = str.replace("，", ",");
            if (str.indexOf("&&") > -1) {
                String[] split = str.split("&&");
                for (int i = 0; i < split.length; i++) {
                    if (i == 0 && split.length > 1) {
                        or = getSubStrs(or, split[i], field, " or ");
                    } else {
                        String[] p1s = split[i].split(",");
                        for (String p : p1s) {

                            and = getSubStrs(and, p, field, " and ");
                        }
                    }
                }
            } else {
                or = getSubStrs(or, str, field, " or ");
            }
        }
        String strOr = or.toString();
        String strAnd = and.toString();
        if (StringUtils.isEmpty(strOr) && StringUtils.isEmpty(strAnd)) {
            return null;
        }
        if (strOr.startsWith(" or ")) {
            strOr = strOr.substring(4);
        }
        if (strAnd.startsWith(" and ")) {
            strAnd = strAnd.substring(5);
        }

        if (StringUtils.isEmpty(strOr)) {
            str = strAnd;
        } else if (StringUtils.isEmpty(strAnd)) {
            str = strOr;
        } else {
            str = "(" + strOr + ") and (" + strAnd + ")";
        }


        return str;
    }

    private static StringBuffer getSubStrs(StringBuffer ssql, String str, String field, String orAnd) {
        String[] p1s = str.split(",");
        for (String p : p1s) {

            if (StringUtils.isEmpty(p))
                continue;

            ssql.append(orAnd);
            ssql.append(field);
            ssql.append(" like concat('%','" + p + "','%')");
        }
        return ssql;
    }

    public static void main(String[] args) {
        System.out.println(getSql("&&123", "test"));

    }
}

